const platform = require('./platform')
let isCall = false

exports.get_quotations = async (base, quote) => {
	let market_prices = {}

	if (!isCall) {
		isCall = true
		console.log('========================')
		for (let market in platform) {
			platform[market].init(market, base, quote)
		}
	}

	for (let market in platform) {
		market_prices[market] = platform[market].data.get('data')
	}
	return market_prices
}

exports.get_best_price = async (market_prices, latest_market, priceValidPercent, latest_ask) => {
	let useful_market = {}, best_market = '', useful_market_ary = []
	for (let market in market_prices) {
		var data = market_prices[market]

		if (data && data.length === 5 && data[1] > 0.00000001 && data[2] > 0.00000001) {
			useful_market[market] = [data[1], data[2]]
			if (latest_market === market) {
				best_market = market
			}
			useful_market_ary.push({
				market,
				ask: data[1],
				bid: data[2],
				historyGap: latest_ask > 0.00000001 ? Math.abs((data[1] - latest_ask)/data[1]) : 0,
				spreads: Math.abs((data[1] - data[2]) / data[1])
			})
		}
	}

	if (best_market === '') {
		var market_ary = Object.keys(useful_market)
		if (market_ary.length === 1) {
			best_market = market_ary[0]
		} else {
			var ary = useful_market_ary.filter(obj => obj.historyGap < priceValidPercent).sort((pre, cur) => pre.spreads - cur.spreads)
			ary[0] && ary[0].market ? best_market = ary[0].market : ''
		}
		// LOG([market_ary, best_market, latest_market])
	}

	return [best_market, useful_market]
}